/*
 *  Copyright 2021-2023 Weibo, Inc.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.rill.flow.executor.controller;

import com.rill.flow.executor.executor.SampleExecutor;
import com.rill.flow.executor.wrapper.ExecutorContext;
import com.rill.flow.executor.wrapper.ExecutorWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;

/**
 * @author yansheng3
 */
@RestController
@Slf4j
public class ExecutorController {

    @Autowired
    private ExecutorWrapper executorWrapper;
    @Autowired
    private SampleExecutor sampleExecutor;


    @RequestMapping(value = "executor.json", method = {RequestMethod.POST}, produces = APPLICATION_JSON_VALUE)
    public Map<String, Object> executorApi(@RequestBody Map<String, Object> data,
                                           @RequestHeader(value = "X-Mode", defaultValue = "sync") String mode,
                                           @RequestHeader(value = "X-Callback-Url", defaultValue = "") String callbackUrl) {
        try {
            ExecutorContext executorContext = ExecutorContext.builder().body(data).callbackUrl(callbackUrl).mode(mode).build();

            return executorWrapper.execute(executorContext, sampleExecutor);
        } catch (Exception e) {
            return Map.of("result_type", "FAILED", "error_msg", "Executor processing failed");
        }
    }
}
